package com.developer.messageme.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.developer.messageme.R;
import com.developer.messageme.util.Util;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;

public class RegisterActivity extends Activity {

	private EditText txtUserName;
	private EditText txtPassword;
	private EditText txtRePassword;
	private EditText txtEmail;
	private Button btnSignUp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_register);
		initalizeComponents();
		registerEvents();
	}

	private void initalizeComponents() {
		txtUserName = (EditText) findViewById(R.id.register_activity_txt_username);
		txtPassword = (EditText) findViewById(R.id.register_activity_txt_password);
		txtRePassword = (EditText) findViewById(R.id.register_activity_txt_repassword);
		txtEmail = (EditText) findViewById(R.id.register_activity_txt_email);
		btnSignUp = (Button) findViewById(R.id.register_activity_btn_signup);
	}

	private void registerEvents() {
		btnSignUp.setOnClickListener(btnSignUpClickListener);
	}

	private View.OnClickListener btnSignUpClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			setProgressBarIndeterminateVisibility(true);
			String userName = txtUserName.getText().toString();
			String password = txtPassword.getText().toString();
			String rePassword = txtRePassword.getText().toString();
			String email = txtEmail.getText().toString();
			if (userName.isEmpty() || password.isEmpty() || rePassword.isEmpty() || email.isEmpty()) {
				Util.showAlertMessage(RegisterActivity.this, "Required values cannot be empty.");
				setProgressBarIndeterminateVisibility(false);
			} else {
				if (!password.equals(rePassword)) {
					Util.showAlertMessage(RegisterActivity.this, "Password mismatch.");
					setProgressBarIndeterminateVisibility(false);
				} else {
					ParseUser user = new ParseUser();
					user.setUsername(userName);
					user.setPassword(password);
					user.setEmail(email);
					user.signUpInBackground(new SignUpCallback() {
						@Override
						public void done(ParseException e) {
							if (e == null) {
								Toast.makeText(RegisterActivity.this, "Registration ok.", Toast.LENGTH_LONG).show();
							} else {
								Toast.makeText(RegisterActivity.this, e.toString(), Toast.LENGTH_LONG).show();
							}
							setProgressBarIndeterminateVisibility(false);
						}
					});
				}
			}
		}
	};

}
